import logging
import time

import jwt

from airflow.patsnap.service import user_service
from airflow.patsnap.util import ldap
from airflow.configuration import conf
from airflow.models import User
from airflow.utils.session import provide_session
from datetime import datetime

log = logging.getLogger(__name__)


@provide_session
def is_path_auth(path, oa_user_name, session=None):
    urls = set()
    have_path = False
    user = User.get_user_by_oausername(oa_user_name, session)
    session.add(user)
    for role in user.roles:
        session.add(role)
        resources = role.resources
        for resource in resources:
            urls.add(resource.url_prefix)

    for url in urls:
        if str(path).startswith(str(url)):
            have_path = True
            break

    return have_path


@provide_session
def apply_token(oa_user_name, session=None):
    # 加密
    payload = {
        "username": oa_user_name,  # 我们需要的信息
        "exp": time.time() + 3600*12  # 设置过期时间，5秒
    }
    jwt_token = jwt.encode(payload,  # payload, 有效载体
                           "kDAmTU2p9E83xw5zzdk9mw",  # 进行加密签名的密钥
                           algorithm="HS512",  # 指明签名算法方式, 默认也是HS256
                           headers=None  # json web token 数据结构包含两部分, payload(有效载体), headers(标头)
                           ).decode('utf-8')  # python3 编码后得到 bytes, 再进行解码(指明解码的格式), 得到一个str
    result = {
        "token": jwt_token,
        "username": oa_user_name
    }
    return result


@provide_session
def login(username, password, session=None):
    if conf.get('webserver', 'login') == 'ldap':
        entry = ldap.verify_username_password(username, password)
        if entry:
            user = User.get_user_by_oausername(username, session)
            if user is None:
                role_ids = [2]
                user_service.add_user(username, username, username, 'ldap', role_ids, session)
            return True
        else:
            return False
    else:
        return False
